<head>
    <title>Welcome</title>
    
    <script src="https://unpkg.com/@vimesh/ui"></script>
    <script src="https://unpkg.com/alpinejs" defer></script>
    <script src="https://unpkg.com/universal-router@9.2.1/universal-router.min.js"></script>

    <script>
        $vui.config.importMap = {
            "*": '../components/${path}${component}.html',
            "page": '../components/spa-pages/${component}.html'
        }
        let data = {
            $route: {},
            routes: [
                { path: '/welcome', component: 'page-welcome' },
                { path: '/blog/:id', component: 'page-blog' },
                { path: '(.*)', component: 'page-welcome' }
            ]
        }
    </script>
    <style>
        [x-cloak] {
            display: none !important;
        }
    </style>
</head>

<body x-cloak x-import="header,footer" x-data="data">
    <vui-header></vui-header>
    <vui-router-view></vui-router-view>
    <vui-footer></vui-footer>
    <template x-component="router-view" x-shtml="$api && $api.pageContent || ''"
        x-import:dynamic="$api && $api.pageToImport">
        <script>
            return {
                router: null,
                pageContent: '',
                pageToImport: null,
                onUrlChange() {
                    let match = window.location.href.match(/#(.*)$/)
                    let fragment = match ? match[1] : ''
                    this.router.resolve({ pathname: fragment }).then(component => {
                        if (component) {
                            let pos = component.indexOf('@')
                            let from = pos !== -1 ? component.substring(pos + 1) : component.replace('-', ':').replace('-', '/')
                            if (pos !== -1) component = component.substring(0, pos)
                            this.pageToImport = from
                            this.pageContent = `<${component}></${component}>`
                        }
                    })
                },
                onMounted() {
                    this.router = new UniversalRouter(this.routes, {
                        context: { self: this },
                        resolveRoute(context, params) {
                            context.self.$route = { params, path: context.pathname }
                            if (typeof context.route.action === 'function') {
                                return context.route.action(context, params)
                            }
                            return context.route.component
                        }
                    })
                    this.onUrlChange()
                    window.addEventListener('popstate', e => this.onUrlChange())
                }
            }
        </script>
    </template>
</body>